package alipay.openplatform.edu.campus.jiuye.api.controller.business;

import alipay.openplatform.edu.campus.jiuye.api.constant.Constant;
import alipay.openplatform.edu.campus.jiuye.api.filter.AdminInterceptor;
import alipay.openplatform.edu.campus.jiuye.api.utils.ContextUtils;
import alipay.openplatform.edu.campus.jiuye.common.enums.ResultCode;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.common.utils.RandomValidateCodeUtil;
import alipay.openplatform.edu.campus.jiuye.model.vo.BllUserInfoVO;
import alipay.openplatform.edu.campus.jiuye.model.vo.ContextVo;
import alipay.openplatform.edu.campus.jiuye.service.dao.ApiResult;
import alipay.openplatform.edu.campus.jiuye.service.iservice.business.IBllUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by suzunshou on 16/9/19.
 */
@RequestMapping(value = "/jiuye/api")
@Controller
public class BllUserInfoController {

    private static final Logger logger = LoggerFactory.getLogger(BllUserInfoController.class);


    @Autowired
    private IBllUserInfoService bllUserInfoService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;


    /**
     * 判断是否登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/isLogin")
    @ResponseBody
    public ApiResult isLogin(HttpServletRequest request) {
        String userId = ContextUtils.getUserId(request);
        if (userId != null) {
            return ApiResult.build(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName());
        }
        return ApiResult.build(ResultCode.AUTH_UNAUTHORIZED.getCode(), ResultCode.AUTH_UNAUTHORIZED.getName());
    }

    /**
     * 登录
     *
     * @param user_name
     * @param user_pwd
     * @param user_code
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult login(@RequestParam(value = "user_name") String user_name, @RequestParam(value = "user_pwd") String user_pwd, @RequestParam(value = "user_code") String user_code) {
        logger.info("登录|UserAdminController|login|params:user_name={},user_pwd={},user_code={}", user_name, user_pwd, user_code);

        try {

            /*加密\登录次数\清除缓存*/
            Integer ticketTimeout = Constant.TICKET_TIMEOUT;
            Map<String, ContextVo> map = AdminInterceptor.getLoginCount();
            //每五分钟清理用户登录次数
            if (map.size() > 0 && ObjectUtils.isNotNull(map.get(user_name))) {
                bllUserInfoService.removeSession(map, user_name);
            }

            ContextVo loginVo;
            if (ObjectUtils.isNotEmpty(map.get(user_name))) {
                loginVo = map.get(user_name);
            } else {
                loginVo = new ContextVo();
            }
            //是否缓存用户登录次数
            if (ObjectUtils.isNotNull(loginVo.getLoginCount())) {
                //登录次数限制+原子类
                int loginCount = Integer.parseInt(loginVo.getLoginCount().toString());
                if (loginCount >= Constant.LOGIN_COUNT) {//如果登录次数超过5次
                    request.getSession().removeAttribute("login");
                    return ApiResult.build(ResultCode.AUTH_LOGIN_ERROR.getCode(), ResultCode.AUTH_LOGIN_ERROR.getName());
                } else {
                    loginVo.getLoginCount().incrementAndGet();
                }
            } else {
                //用户登录次数
                loginVo.setLoginCount(new AtomicInteger(0));
                loginVo.getLoginCount().incrementAndGet();
                //产生失效时间
                Timestamp createTime = new Timestamp(System.currentTimeMillis());
                Calendar cal = Calendar.getInstance();
                cal.setTime(createTime);
                cal.add(Calendar.SECOND, ticketTimeout);
                Timestamp recoverTime = new Timestamp(cal.getTimeInMillis());
                loginVo.setRecoverTime(recoverTime);
            }

            map.put(user_name, loginVo);

            //每五分钟清理用户登录次数
            if (map.size() > 0 && ObjectUtils.isNotNull(map.get(user_name))) {
                bllUserInfoService.removeSession(map, user_name);
            }
            //验证码
            String validateCode = (String) request.getSession().getAttribute("login");
            logger.debug("=validateCode=={}=", validateCode);
            if (StringUtils.isEmpty(validateCode) || !validateCode.equalsIgnoreCase(user_code)) {
                request.getSession().removeAttribute("login");
                return ApiResult.build(ResultCode.CAPTCHA_ERR.getCode(), ResultCode.CAPTCHA_ERR.getName());
            }

            BllUserInfoVO bllUserInfoVO = new BllUserInfoVO();
            bllUserInfoVO.setUserName(user_name);
            //md5
            user_pwd = DigestUtils.md5DigestAsHex(user_pwd.getBytes());
            bllUserInfoVO.setUserPwd(user_pwd);
            bllUserInfoVO = bllUserInfoService.selectByUserNameAndPassWord(bllUserInfoVO);
            //登录并存入缓存
            if (ObjectUtils.isNotNull(bllUserInfoVO)) {
                Integer userId = bllUserInfoVO.getUserId();
                request.getSession().setAttribute(ContextUtils.SESSIONUTILS, userId.toString());
                logger.info("登录成功,设置session的值为ContextUtils.SESSIONUTILS={}", userId);
                //清除验证码
                request.getSession().removeAttribute("login");
                return ApiResult.build(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName());
            }
            //清除验证码,重新生成(前台调用)
            request.getSession().removeAttribute("login");
            return ApiResult.build(ResultCode.AUTH_LOGIN_FAILED.getCode(), ResultCode.AUTH_LOGIN_FAILED.getName());
        } catch (Exception e) {
            logger.error("登录|UserAdminController|login|params:user_name={},user_pwd={},user_code={},message={},stackTrace={}", user_name, user_pwd, user_code, e.getMessage(), e);
            return ApiResult.build(ResultCode.SYSTEM_EXCEIPTION.getCode(), ResultCode.SYSTEM_EXCEIPTION.getName());
        }
    }

    /**
     * 注销
     *
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public ApiResult logout(HttpServletRequest request) {
        logger.info("登出|UserAdminController|logout");
        request.getSession().removeAttribute(ContextUtils.SESSIONUTILS);
        return new ApiResult().build(ResultCode.STATUS_OK.getCode(), ResultCode.STATUS_OK.getName());
    }

    /**
     * 登录获取验证码
     */
    @RequestMapping("/getImageCode")
    @ResponseBody
    public String getImageCode() {
        response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
        response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Set-Cookie", "name=value; HttpOnly");//设置HttpOnly属性,防止Xss攻击
        response.setDateHeader("Expire", 0);
        RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
        randomValidateCode.getRandcode(request, response, "login");// 输出图片方法
        return "";
    }

}
